package com.example.myapplication.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.util.Log;
import android.view.SurfaceControlViewHost;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.service.HelloService;

import java.util.Objects;
//
//public class MainActivity extends Activity {
//    //

/// /    @Override
/// /    protected void onCreate(Bundle savedInstanceState) {
/// /        super.onCreate(savedInstanceState);
/// /        EdgeToEdge.enable(this);
/// /        setContentView(R.layout.activity_main);
/// /        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
/// /            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
/// /            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
/// /            return insets;
/// /        });
/// /    }
//    String msg = "Android : ";
//    Button intentButton = null;
//
//    /**
//     * 当活动第一次被创建时调用
//     */
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        Log.d(msg, "The onCreate() event");
//
//        // 服务
//        Button startButton = findViewById(R.id.start);
//        Button endButton = findViewById(R.id.end);
//
//        startButton.setOnClickListener(this::startService);
//        endButton.setOnClickListener(this::stopService);
//
//        intentButton = findViewById(R.id.sendIntent);
//        // 广播
//        intentButton.setOnClickListener(this::broadcastIntent);
//
//    }
//
//    /**
//     * 当活动将被销毁时调用
//     */
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        Log.d(msg, "The onDestroy() event");
//    }
//
//    // 点击打开百度网站
//    @SuppressLint("QueryPermissionsNeeded")
//    public void startService(View view) {
//        // 创建一个 Intent 用于打开网页
//        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://guilin-culture-heritage.oss-cn-beijing.aliyuncs.com/heritage/sanhuajiu.jpg"));
//
//        // 检查是否有 Activity 可以处理该 Intent
//        if (intent.resolveActivity(getPackageManager()) != null) {
//            // 有合适的 Activity，启动它
//            startActivity(intent);
//        } else {
//            // 没有合适的 Activity，给用户提示
//            Toast.makeText(this, "没有找到可以打开该网页的应用", Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    // Method to stop the service
//    public void stopService(View view) {
//        Intent read1=new Intent();
//        read1.setAction(android.content.Intent.ACTION_VIEW);
//        read1.setData(ContactsContract.Contacts.CONTENT_URI);
//        startActivity(read1);
//    }
//
//    // 按下button打开百度
//
//    public void broadcastIntent(View view) {
//        try {
//            Intent intent = new Intent();
//            intent.setAction("com.example.DEFINE");
//            sendBroadcast(intent);
//        } catch (Exception e) {
//            System.out.println();
//        }
//
//    }
//
//    // 跳转到广播接收的页面
//    public void ToBroadcast(View view) {
//        Intent intent = new Intent(this, BroadcastActivity.class);
//        startActivity(intent);
//    }
//
//    // 跳转到IPC服务页面
//    public void ToService(View view) {
//        Intent intent = new Intent(this, ServiceActivity.class);
//        startActivity(intent);
//    }
//
//    /**
//     * 当活动即将可见时调用
//     */
//    @Override
//    protected void onStart() {
//        super.onStart();
//        Log.d(msg, "The onStart() event");
//    }
//
//    /**
//     * 当活动可见时调用
//     */
//    @Override
//    protected void onResume() {
//        super.onResume();
//        Log.d(msg, "The onResume() event");
//    }
//
//    /**
//     * 当其他活动获得焦点时调用
//     */
//    @Override
//    protected void onPause() {
//        super.onPause();
//        Log.d(msg, "The onPause() event");
//    }
//
//    /**
//     * 当活动不再可见时调用
//     */
//    @Override
//    protected void onStop() {
//        super.onStop();
//        Log.d(msg, "The onStop() event");
//    }
//}
// 在 Activity 中创建 SurfaceControlViewHost
public class MainActivity extends AppCompatActivity {
    private SurfaceControlViewHost mViewHost;
    private WindowManager mWindowManager;
    private static final int OVERLAY_PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWindowManager = getSystemService(WindowManager.class);

        // 检查并请求悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE);
            } else {
                // 已有权限，创建悬浮窗
                createFloatingWindow();
            }
        } else {
            // Android 6.0以下无需权限
            createFloatingWindow();
        }
    }

    private void createFloatingWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            mViewHost = new SurfaceControlViewHost(
                    this,
                    mWindowManager.getDefaultDisplay(),
                    getWindow().getAttributes().token
            );

            TextView textView = new TextView(this);
            textView.setText("Hello from SurfaceControlViewHost");
            textView.setBackgroundColor(Color.WHITE);

            mViewHost.setView(textView, 400, 200);

            // 使用正确的 WindowManager.LayoutParams
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    400,
                    200,
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                            WindowManager.LayoutParams.TYPE_PHONE,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

            // 添加到窗口管理器
            try {
                mWindowManager.addView(mViewHost.getView(), params);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "添加悬浮窗失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    createFloatingWindow();
                } else {
                    Toast.makeText(this, "需要悬浮窗权限才能显示内容", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        if (mViewHost != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                try {
                    mWindowManager.removeView(mViewHost.getView());
                    mViewHost.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}